/****************************************************************************\
 * @file    Joystick.c
 * @author  马新硕
 * @date    2022/10/12
 * @brief   摇杆和按键的驱动
 * @note    ADC读取摇杆模拟量
 ******************************************************************************
 * @attent  
 ****************************************************************************/

#include "Joystick.h"
#include "adc.h"

uint32_t ADC_Value[40];
JoyStick_t JoyStick;

void Joystick_Init(void)
{
  HAL_ADCEx_Calibration_Start(&hadc1);                                                  //ADC1
  HAL_Delay(100);
  HAL_ADC_Start_DMA(&hadc1, (uint32_t*)&ADC_Value, 40);
}

void JoyStick_GetData(void)
{
  static uint8_t first_flag = 2;
  uint8_t i;
  uint32_t adx,ady;
  static uint16_t x_zero, y_zero;
  int16_t x_relative, y_relative;
  
  for(i=0,adx=0,ady=0; i < 40;)
  {
    adx += ADC_Value[i++];
    ady += ADC_Value[i++];
  }
  adx /= 20;
  ady /= 20;
  
  if(first_flag)
  {
    x_zero = adx;
    y_zero = ady;
    JoyStick.JoyX = 0;
    JoyStick.JoyY = 0;
    first_flag--;
  }
  else
  {
    x_relative = adx-x_zero;
    y_relative = ady-y_zero;
    if(x_relative < 0){JoyStick.JoyX = (float)x_relative/x_zero * 128;}
    else{JoyStick.JoyX = (float)x_relative/(4096-x_zero) * 128;}
    if(y_relative < 0){JoyStick.JoyY = -(float)y_relative/y_zero * 128;}
    else{JoyStick.JoyY = -(float)y_relative/(4096-y_zero) * 128;}
  }
  
  if(HAL_GPIO_ReadPin(ButtonA_GPIO_Port, ButtonA_Pin) == RESET){JoyStick.ButtonA = 1;}
  else{JoyStick.ButtonA = 0;}
  if(HAL_GPIO_ReadPin(ButtonB_GPIO_Port, ButtonB_Pin) == RESET){JoyStick.ButtonB = 1;}
  else{JoyStick.ButtonB = 0;}
  if(HAL_GPIO_ReadPin(ButtonC_GPIO_Port, ButtonC_Pin) == RESET){JoyStick.ButtonC = 1;}
  else{JoyStick.ButtonC = 0;}
  if(HAL_GPIO_ReadPin(ButtonD_GPIO_Port, ButtonD_Pin) == RESET){JoyStick.ButtonD = 1;}
  else{JoyStick.ButtonD = 0;}
}
